package org.edu.modules.common.util;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;

import java.io.ByteArrayOutputStream;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author lbh
 * @Date 2025/4/27 下午2:47
 * @Version 1.0
 */
public class QRCodeUtils {

    public static byte[] generateQRCode(String text, int width, int height) throws Exception {
        Map<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET,  "UTF-8"); // 支持中文
        hints.put(EncodeHintType.MARGIN,  1); // 二维码边距

        QRCodeWriter writer = new QRCodeWriter();
        BitMatrix bitMatrix = writer.encode(text,  BarcodeFormat.QR_CODE, width, height, hints);

        try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
            MatrixToImageWriter.writeToStream(bitMatrix,  "PNG", os);
            return os.toByteArray();
        }
    }
    // 新增方法：返回Base64字符串
    public static String generateQRCodeBase64(String text, int width, int height) throws Exception {
        byte[] bytes = generateQRCode(text, width, height); // 调用原有生成方法
        return Base64.getEncoder().encodeToString(bytes);
    }
}
